<template>
  <div class="app-container">
    <el-form
      ref="dataForm"
      :rules="rules"
      :model="temp"
      label-position="left"
      label-width="110px"
    >
      <el-form-item label="文章标题：" prop="articleTitle">
        <el-input v-model="temp.articleTitle" placeholder="请输入文章标题" />
      </el-form-item>

      <el-form-item label="文章简介：">
        <el-input v-model="temp.articleIntroduction " placeholder="请输入文章简介" />
      </el-form-item>

      <el-form-item label="文章类型：" prop="articleTypeId">
        <el-select v-model="temp.articleTypeId" class="filter-item" placeholder="请选择文章类型">
          <el-option v-for="item in articleTypeOptions" :key="item.articleTypeId" :label="item.articleTypeName" :value="item.articleTypeId" />
        </el-select>
      </el-form-item>

      <el-form-item label="文章封面：" prop="avatarUrl">
        <el-upload
          class="avatar-uploader"
          action="/v2/editor/image"
          :show-file-list="false"
          :headers="headers"
          list-type="picture-card"
          :on-success="onCoverUploadSuccess"
          :before-upload="beforeCoverUpload"
        >
          <img v-if="temp.articleCover" width="100%" :src="temp.articleCover" class="avatar">
          <i v-else class="el-icon-plus" />
        </el-upload>
      </el-form-item>
    </el-form>
    <div ref="editor" style="text-align:left;margin-bottom: 20px;" />

    <el-button type="primary" @click="editorStatus==='create'?createData():updateData()">
      {{ textMap[editorStatus] }}
    </el-button>
  </div>
</template>

<script>
import E from 'wangeditor'
import { getAccessToken } from '@/utils/auth'
import { fetchArticleDetail, fetchArticleContent, fetchArticleTypeList, saveArticle, saveArticleContent, uploadImage } from '@/api/article'

export default {
  name: 'ArticleEditor',
  data() {
    return {
      // 此处hack，需要考虑更好的方式
      headers: {
        'accessToken': getAccessToken()
      },
      listLoading: true, // 加载中
      articleTypeOptions: [
      ],
      editor: undefined,
      // 数据模板
      temp: {
        articleId: '',
        articleContentId: '',
        articleTitle: '',
        articleIntroduction: '',
        articleCover: '',
        articleTypeId: ''
      },
      articleContentText: '',
      // 数据编辑规则
      rules: {
        articleTitle: [{ required: true, message: '文章标题为必填项', trigger: 'blur' }],
        articleTypeId: [{ required: true, message: '文章类型为必填项', trigger: 'blur' }]
      },
      // create or update
      editorStatus: 'update',
      // 对话框标题
      textMap: {
        update: '更新文章',
        create: '发布文章'
      }
    }
  },
  mounted() {
    var editor = new E(this.$refs.editor)
    this.editor = editor
    const that = this
    editor.customConfig.customUploadImg = function(files, insert) {
      // files 是 input 中选中的文件列表
      // 注意这里 files 中的第 0 个元素才是当前上传的文件对象
      // insert 是获取图片 url 后，插入到编辑器的方法
      const formData = new FormData()
      formData.append('file', files[0])
      uploadImage(formData).then(response => {
        insert(response.data.src)
      }).catch(() => {
        that.$notify({
          title: '提示',
          message: '图片上传失败',
          type: 'warning',
          duration: 2000
        })
      })
    }
    editor.customConfig.onchange = (html) => {
      this.articleContentText = html
    }
    editor.create()
  },
  created() {
    const articleId = this.$route.params.articleId
    if (articleId) {
      this.editorStatus = 'update'
      fetchArticleTypeList().then(response => {
        this.articleTypeOptions = response.data
      })
      fetchArticleDetail(articleId).then(response => {
        console.log(response)
        this.temp = response.data
        fetchArticleContent(this.temp.articleContentId).then(response => {
          this.articleContentText = response.data.articleContentText
          console.log(this.articleContentText)
          this.editor.txt.html(this.articleContentText)
        })
      })
    } else {
      this.editorStatus = 'create'
      this.temp.articleCover = '/img/default_resource_cover.jpg'
      fetchArticleTypeList().then(response => {
        this.articleTypeOptions = response.data
        this.temp.articleTypeId = this.articleTypeOptions[0].articleTypeId
      })
    }
  },
  methods: {
    getContent: function() {
      alert(this.articleContentText)
    },
    createData: function() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (!this.articleContentText) {
            this.$message({
              title: '提示',
              message: '请输入文章内容',
              type: 'warning',
              duration: 2000
            })
            return
          }
          const articleContent = {
            articleContentText: this.articleContentText
          }
          saveArticleContent(articleContent).then(response => {
            const articleContentId = response.data.articleContentId
            this.temp.articleContentId = articleContentId
            saveArticle(this.temp).then(() => {
              const that = this
              this.$notify({
                title: '提示',
                message: '发布成功',
                type: 'success',
                duration: 2000,
                onClose: () => {
                  that.$router.push({ path: '/article/articleList' })
                }
              })
            })
          })
        }
      })
    },
    updateData: function() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (!this.articleContentText) {
            this.$message({
              title: '提示',
              message: '请输入文章内容',
              type: 'warning',
              duration: 2000
            })
            return
          }
          const articleContent = {
            articleContentId: this.temp.articleContentId,
            articleContentText: this.articleContentText
          }
          saveArticleContent(articleContent).then(() => {
            saveArticle(this.temp).then(() => {
              const that = this
              this.$notify({
                title: '提示',
                message: '更新成功',
                type: 'success',
                duration: 2000,
                onClose: () => {
                  that.$router.push({ path: '/article/articleList' })
                }
              })
            })
          })
        }
      })
    },
    beforeCoverUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!(isJPG || isPNG)) {
        this.$message.error('上传的封面图片只能是jpg或png格式')
      }
      // var windowURL = window.URL || window.webkitURL
      // this.temp.avatarUrl = windowURL.createObjectURL(file)
      // if (!isLt2M) {
      //   this.$message.error('上传的头像图片大小不能超过2MB')
      // }
      return (isJPG || isPNG) && isLt2M
    },
    onCoverUploadSuccess(res, file) {
      this.temp.articleCover = res.data.src
    }
  }
}
</script>
